<?php

namespace app\api\controller\xykeep;
use app\common\controller\Api;

use app\api\model\xykeep\Goods as GoodsModel;
use app\api\model\xykeep\Category as CategoryModel;
use app\common\model\Comment as CommentModel;
use think\Db;

/**
 * XYkeep商品接口
 */
class Goods extends Api
{
    protected $noNeedLogin = ['lists','detail','categories'];
    protected $noNeedRight = ['*'];
    
	/**
	 * 商品列表
	 */
	public function lists()
    {
    	$params = $this->request->post();
        $data = GoodsModel::getList($params);
        $this->success('商品列表', $data);
    }

//    public function getLists()
//    {
//        $params = $this->request->get();
//        $data = GoodsModel::where([
//            'status' => 'up'
//        ])->with('skuPrice')->paginate();
//        foreach ($data as $k => &$v) {
//            $v = $v->append(['sku']);
//        }
//        $this->success('商品列表', $data);
//    }
	
    /**
     * 商品详情
     */
    public function detail()
    {
        $id = $this->request->get('id');
        $detail = GoodsModel::getDetail($id);

        if(!$detail){
            $this->error('商品不存在！');
        }

        // 添加浏览记录
        $userId = $this->auth->id; // 获取当前登录用户ID
        if ($userId) { // 只有登录用户才记录浏览历史
            $historyData = [
                'user_id'     => $userId,
                'goods_id'    => $id,
                'update_time' => date('Y-m-d H:i:s')
            ];

            // 检查是否已有浏览记录
            $exists = Db::name('browse_history')
                ->where('user_id', $userId)
                ->where('goods_id', $id)
                ->find();

            if ($exists) {
                // 如果存在，只更新更新时间
                Db::name('browse_history')
                    ->where('id', $exists['id'])
                    ->update(['update_time' => date('Y-m-d H:i:s')]);
            } else {
                // 如果不存在，创建新记录
                $historyData['create_time'] = date('Y-m-d H:i:s');
                Db::name('browse_history')->insert($historyData);
            }
        }

        //商品评论
        $detail['comment'] = (new CommentModel())->where([
            'target_id' => $detail['id'],
            'type' => 'goods'
        ])->select();

        $this->success('商品详情', $detail);
    }

    /**
     * 商品分类
     */
    public function categories(){
        $params = $this->request->get();
        $data = CategoryModel::getAllCategory($params);
        $this->success('商品分类', $data);
    }

    /**
     * 获取浏览足迹商品列表
     */
    public function browseHistory()
    {
        $userId = $this->auth->id;

        // 获取浏览过的商品ID（按时间倒序）
        $data = Db::name('browse_history')
            ->where('user_id', $userId)
            ->order('update_time', 'desc')
            ->paginate();

        $data->each(function ($item, $key) {
           return GoodsModel::getDetail($item['goods_id']);
        });

        $this->success('浏览足迹', $data);
    }

}